import re
from tikz.circuit import Circuit, Node, Chain, Coordinate


class AmplifierCircuit(Circuit):
    def __init__(self, name, loc=None, in1=None, in2=None, out=None):
        super().__init__(name=name, ports=["in1", "in2", "out"])
        if isinstance(loc, Coordinate):
            self.loc = loc
        elif loc is not None:
            self.loc = Coordinate(loc)
        else:
            self.loc = Coordinate([1, 1])

        oa = Node("op amp", label="A1")
        line = Chain("short")
        r1 = Chain("R=$R_1$")
        r2 = Chain("R=$R_2$")
        c = Chain("C=$C$")

        self.add_path(oa, Node(content="$A_1$"), start=self.loc, need_end=False)

        self.add_path(r1, "left", f"coordinate({self.in1})", start=oa('-'), need_end=False)
        self.add_path(r2, "down", f"coordinate({self.in2})", start=oa('+'), need_end=False)

        self.add_path(line, "++(0, 1)", start=oa('-'), need_end=False)
        self.add_element(c, to_loc=oa.out)
        self.add_element(Node("left"), direction="left")

        self.add_path(f"coordinate({self.out})", start=oa.out, need_end=False)

        self.in1 = Coordinate(self.in1)
        self.in2 = Coordinate(self.in2)
        self.out = Coordinate(self.out)
        if in1 is not None:
            self.add_path(f"-|{self.in1}", start=in1, need_end=False)
        if in2 is not None:
            self.add_path(f"-|{self.in2}", start=in2, need_end=False)
        if out is not None:
            self.add_path(f"-|{self.out}", start=out, need_end=False)


omega = r'\omega'

amplifier_circuit1 = AmplifierCircuit("ac1")
print(amplifier_circuit1)
amplifier_circuit = AmplifierCircuit("ac2", amplifier_circuit1.out + (4, -2), in1=amplifier_circuit1.out)
print(amplifier_circuit)
amplifier_circuit = AmplifierCircuit("ac3", amplifier_circuit1.out + (4, 2), in1=amplifier_circuit1.out)
print(amplifier_circuit)

#
# draw(oa, Node(loc=None, label="A2", content="$A_1$"))
# draw(oa('-'), r1, Node("left", loc=(-2, 0), content="$u_i$"))
# draw(oa('+'), r2, gnd)
# draw(oa('-'), "--", Path(Coordinate((0, 1)), c, oa.out))
# draw(node1('-'), to, node2)
# draw(node1.n, to, node2)

# \draw (0, 0) node[op amp](A1){} node {$A_1$};
# \draw (A1.-) to[R=$R_1$,-o] ++(-2, 0) node[left] {$u_i$};
# \draw (A1.+) to[R=$R_2$] ++(0, -2) node[ground](GND){};
# \draw (A1.-) -- ++(0, 1) coordinate(temp) to[C=$C$] (temp -| A1.out)--(A1.out) ++(0, 1) node[left] {$u_1$};
# \draw (A1.out) to[short,-o] ++(2,0) node[right] {$u_o$};
